package com.study.jdbc.mydbutils;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
* @Name: BeanListHandle
* @Description: ResultSetHandler结果处理器接口实现类：将sql查询结果(多条记录)封装到List<JavaBean>集合中
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-2-19 下午10:44:25 
* @Version: V1.0
 */
public class BeanListHandle implements ResultSetHandler {
	
	private Class clazz ;

	public BeanListHandle(Class clazz) {
		this.clazz = clazz;
	}

	@Override
	public Object handle(ResultSet rs) {
		List list = null ;
		if(rs != null) {
			//创建封装结果集合对象
			list = new ArrayList() ;
			try {
				while(rs.next()) {
					//创建JavaBean实例对象
					Object bean = clazz.newInstance() ;
					//获取查询结果元信息对象
					ResultSetMetaData metaData = rs.getMetaData() ;
					//获取结果集合中每条记录中字段的个数
					int columnCount = metaData.getColumnCount() ;
					for (int i = 0; i < columnCount; i++) {
						//将字段内容封装到JavaBean中
						String fieldName = metaData.getColumnName(i+1) ;
						Object fieldValue = rs.getObject(i+1) ;
						Field field = clazz.getDeclaredField(fieldName) ;
						field.setAccessible(true) ;
						field.set(bean, fieldValue) ;
					}
					list.add(bean) ;
				}
			} catch (Exception e) {
				e.printStackTrace() ;
			}
		}
		return list;
	}
	

}

